/* 
 * select component
 * @author luweijun
 */
(function(){
    var Category = function() {
        this.settings = null;
        this.conditions = null;
        this.datas = null;
        this.view = null;
        this.selectIds = [];
        this.placeHolder = [];
        this.initView();
        this.groupOnClick = _.bind(this.groupOnClick,this);
        this.clearNext = _.bind(this.clearNext, this);
    };
    
    Category.instance = null;
    Category.DomId = 0;
    Category.Map = ['顶','二','三','四','五','六','七','八'];
    Category.getInstance = function() {
        if (null == this.instance) {
            this.instance = new Category();
        } else {
            this.instance.clear();
        }
        return this.instance;
    };
    
    Category.prototype = {
          query : function(dataName) {
            var ret = {};
            ret[dataName] = [];
            if (typeof dataName == 'string' && typeof this.data[dataName] == 'object') {
                var selecteds = this.data[dataName];
                ret[dataName] = selecteds;
                return ret;
            }
            return ret;
        },
         getSingleSelect : function(gName,placeName,Name,sty) {
            var style = sty || '';
            return {
                    'conditions' : [
                            {
                                property: 'Single',
                                contents : [
                                   {
                                        gn : gName,
                                        placeholder : placeName,
                                        eventsFn : [],
                                         name : Name,
                                        'class' : 'select',
                                         style : style
                                    }
                                ]
                            }
                        ]
                    };
        },
        
	buildCategoryView : function(level) {
            if (typeof level != 'number') {
                level = 0;
            }
            var name = Category.Map[level]+'级类别';
            var conditions =  this.getSingleSelect(name,name,'cat'+Category.Map[level],'width:100px;');
            var datas = QY.Analytics.buss.BasicData.query('mobile_play_platform');
	    var data = {};
	    data['platform'] = datas['mobile_play_platform'];
            var html = QY.Analytics.ui.Select.getInstance().build(conditions,data);
            return html;
        },
        
        afterRenderCategoryView : function() {
            QY.Analytics.ui.Select.instance.after();
            this.selecteds.push('platform');
        },
        
        obtainId : function() {
            return  ++Category.DomId + '_category_select';
        },
        
        initView : function() {
            var view = $('<span class="select"></div>');
            this.view = view;
        },
        
        defaultConditions : function() {
	    var _this = this;
            return [
                        {
                            property : 'Group',
                            name : '筛选条件',
                            contents : [
                                        {
                                            gn : '',
                                            placeholder : '一级类目',
                                            eventsFn : [_this.groupOnClick],
                                            name : 'tc',
                                            'class' : 'select',
                                            style : 'width:100px;'
                                        },
                                        {
                                            gn : '',
                                            placeholder : '二级类目',
                                            eventsFn : [_this.groupOnClick],
                                             name : 'pc',
                                            'class' : 'select',
                                             style : 'width:100px;'
                                        },
                                        {
                                            gn : '',
                                            placeholder : '三级类目',
                                            eventsFn : [_this.groupOnClick],
                                             name : 'c',
                                            'class' : 'select',
                                             style : 'width:100px;'
                                        },
                                        {
                                            gn : '',
                                            placeholder : '四级类目',
                                            eventsFn : [_this.groupOnClick],
                                             name : 'cc',
                                            'class' : 'select',
                                             style : 'width:100px;'
                                        }
                                ]
                        },
                        {
                            property: 'Single',
                            contents : [        
                                           {
                                                gn : '一级类目',
                                                placeholder : '一级类目',
                                                eventsFn : [],
                                                 name : 'tc',
                                                'class' : 'select',
                                                 style : ''
                                            } 
                                    ]
                        }
                    ];
        },
        
        groupOnClick : function(elementId, me) {
            this.clearNext(elementId, me);

            var prevId = this.getPrevId(elementId, me);
            if (false === prevId) {
		 var html = [];
		 html.push('<option value=""></option>');
           
		var name = me.attr("name");
		var data = this.datas[name];
		if (data == undefined) {
		    var da = QY.Analytics.buss.BasicData.query(name);
		    data = da[name];
		}
		for (var i=0,len=data.length; i< len; i++) {
			html.push('<option value="'+ data[i].id +'" index='+data[i].index+'>'+data[i].name+'</option>');
		}
		me.html(html.join(''));
		return;
	    }

            var parentIndex = $("select[id="+prevId+"]").find("option:selected").attr("index");
            var parentName = $("#"+prevId).attr("name") + '_id';
            
            var name = me.attr("name");
            
            var data = this.datas[name];
	    if (data == undefined) {
	        var da = QY.Analytics.buss.BasicData.query(name);
	        data = da[name];
	    }

            var html = [];
            html.push('<option value=""></option>');
           
            for (var i=0,len=data.length; i< len; i++) {
                if (data[i][parentName] && data[i][parentName] == parentIndex) {
                    html.push('<option value="'+ data[i].id +'" index='+data[i].index+'>'+data[i].name+'</option>');
                }
            }
            
            me.html(html.join(''));
        },
        
        getPrevId : function(elementId,me) {
            var de = 1,idArr = [];
            me.parent().find("select").each(function(index,ele){
                idArr.push($(ele).attr("id"));
            });
            var prevId = elementId.substr(0,elementId.length-1) + (parseFloat(elementId.substr(elementId.length-1))-de);
            if (QY.Analytics.util.Fn.inArray(prevId, idArr) && $("#"+prevId).length == 1 && $("select[id="+prevId+"]").val() != '') {
                return prevId;
            } else {
                if (de < idArr.length) {
                    return this.getPrevId(prevId, $("#"+prevId));
                }
            }
            return false;
        },
        
        clearNext : function(elementId,me) {
            var de = 1,idArr = [];
            me.parent().find("select").each(function(index,ele){
                idArr.push($(ele).attr("id"));
            });
            var nextId = parseFloat(elementId.substr(elementId.length-1));

	    for (var i=0,len=idArr.length;i<len;i++) {
		var num = parseFloat(idArr[i].substr(idArr[i].length-1));
		if (num > nextId) {
			var DomId = idArr[i];
			$("select[id="+DomId+"]").val("");
			$("#s2id_"+DomId).find("a span").html($("#"+DomId).attr("placeholder"));
		}
	    }
            
        },
        
        build : function(cond, datas) {
            if (cond && typeof cond['setting'] == 'object') {
                this.settings = cond['setting'];
            }
            
            var conditions = [];
            if (cond && typeof cond['conditions'] == 'object') {
                conditions = cond['conditions'];
            }
            
            if (typeof conditions == "object" && conditions.length > 0) {
                this.conditions = this.defaultConditions();
		for (var i=0,len=conditions.length;i<len;i++) {
			this.conditions.splice(this.conditions.length,0,conditions[i]);
		}
            } else {
                this.conditions = this.defaultConditions();
            }

            this.datas = datas;
            for (var i in this.conditions) {
                var fn = 'build' + this.conditions[i].property;
                var viewobj = this[fn].call(this, this.conditions[i]);
                $(viewobj).appendTo(this.view);
            }
            return this.view;
        },
        
        buildGroup : function(params) {
            var gname = params.name,contents = params.contents;
            var groupView = $('<div class="group" id="'+ this.obtainId() +'"></div>');
            var html = [];
            html.push('<div class="select-line">');
            for (var i=0,len=contents.length; i<len; i++) {
                    var id = this.obtainId();
                    if (typeof contents[i].gn != "undefined" && contents[i].gn.trim().length > 0) {
                        html.push('<label class="control-label" for="'+ id +'">'+contents[i].gn);
                    }
                    html.push('<select id="' + id + '" class="' + contents[i]['class'] + '" name="' + contents[i].name + '" style="' + contents[i].style + '" placeholder="'+ contents[i]['placeholder'] +'">');
                    html.push('<option value=""></option>');
                    
                    var name = contents[i].name;
                    if (typeof this.datas[name] !== "undefined" && this.datas[name].length > 0) {
                        for (var d=0,dl=this.datas[name].length; d<dl; d++) {
                            var da = this.datas[name][d];
                            var sv = Url.getURLParameters(name);
                            var sh = sv == da.id ? ' selected="true"' : '';
                            html.push('<option value="'+ da.id +'"'+sh+'" index='+da.index+'>'+da.name+'</option>');
                        }
                    }
                    
                    html.push('</select>');
                    if (typeof contents[i].gn != "undefined" && contents[i].gn.trim().length > 0) {
                        html.push('</label>');
                    }
                    
                    if (contents[i].eventsFn.length > 0) {
                        for (var n=0,m=contents[i].eventsFn.length; n<m; n++) {
                            var fn = contents[i].eventsFn[n];
                            this.listen(id, fn);
                        }
                    }
                    
                    this.selectIds.push(id);
                    this.placeHolder.push(contents[i].placeholder);
                }
                html.push("</div>");
                groupView.html(html.join(''));
                return groupView;
        }, 
        
        buildSingle : function(params) {
            var contents = params.contents,html = [];
            for (var i=0,len=contents.length; i<len; i++) {
                    var id = QY.Analytics.obtainId();
                    html.push('<div class="group">');
                    html.push('<label class="control-label" for="'+ id +'">');
                    html.push('<select id="' + id + '" class="' + contents[i]['class'] + '" name="' + contents[i].name + '" style="' + contents[i].style + '" placeholder="'+ contents[i]['placeholder'] + '">');
                    html.push('<option value=""></option>');
                    
                    var name = contents[i].name;
                    if (typeof this.datas[name] !== "undefined" && this.datas[name].length > 0) {
                        for (var d=0,dl=this.datas[name].length; d<dl; d++) {
                            var da = this.datas[name][d];
                            var sv = Url.getURLParameters(name);
                            var sh = sv == da.id ? ' selected="true"' : '';
                            html.push('<option value="'+ da.id +'"'+sh+'" index='+da.index+'>'+da.name+'</option>');
                        }
                    }
                    
                    html.push('</select>');
                    html.push('</label>');
                    html.push('</div>');
                    if (contents[i].eventsFn.length > 0) {
                        for (var n=0,m=contents[i].eventsFn.length; n<m; n++) {
                            var fn = contents[i].eventsFn[n];
                            this.listen(id, fn);
                        }
                    }
                    this.placeHolder.push(contents[i].placeholder);
                    this.selectIds.push(id);
            }
            return html.join('');
        },
        
        listen : function(elementId, callFn) {
            $(".query-container").delegate("#s2id_"+elementId,"mouseenter",function(){
               callFn(elementId, $("#"+elementId)); 
            });
        },
        
        getSelectIds : function() {
            return this.selectIds;
        },
        
        after : function() {
            for (var i=0,len=this.selectIds.length; i<len; i++) {
                var tip = this.placeHolder[i];
                 $('#' + this.selectIds[i]).select2({
                    placeholder: tip,
                    allowClear: true
                });
            }
        },
        
        clear : function() {
            this.settings = null;
            this.conditions = null;
            this.datas = null;
            this.view = null;
            this.selectIds.length = 0;
            this.placeHolder.length = 0;
            this.initView();
        }
    };
    
    window.Category = Category;
})();


